package org.bigdata.framework.core.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.bigdata.framework.core.model.ClassesOnline;
import org.bigdata.framework.core.model.Course;
import org.bigdata.framework.core.model.Menu;
import org.bigdata.framework.core.model.Permission;
import org.bigdata.framework.core.model.User;
import org.bigdata.framework.core.model.UserRole;
import org.bigdata.framework.core.protocol.IBaseService;
import org.bigdata.framework.core.protocol.IPublicService;
import org.bigdata.framework.core.utils.DateUtils;
import org.bigdata.framework.core.utils.FileDownloadUtil;
import org.bigdata.framework.core.utils.IdWorker;
import org.bigdata.framework.core.utils.MD5;
import org.bigdata.framework.core.utils.TreeJsion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.google.code.kaptcha.Constants;

import springfox.documentation.annotations.ApiIgnore;

@ApiIgnore
@Controller
public class UserController extends BaseController{


	@Autowired
	private IBaseService baseService;
	@Autowired
	private IPublicService publicService;
	
	
	private static String FILESERVER = "";
	private static String FILEPATH = "";
	
	IdWorker idWorker = new IdWorker(2);

	static {
		Properties properties_config = new Properties();
		InputStream in_config = SystemController.class.getClassLoader().getResourceAsStream("config.properties");
		try {
			properties_config.load(in_config);

			FILESERVER = properties_config.getProperty("file.server");
			FILEPATH = properties_config.getProperty("file.path");
		} catch (IOException e) {
		}
	}
	
	@RequestMapping("login.html")
	public String toLogin(HttpServletRequest request, Model model) {

		return "/modules/login";
	}

	@RequestMapping("main.html")
	public String toMain(HttpServletRequest request, Model model) {
		return "/modules/main";
	}
	
	// geren_geRen_ziLiao.html
	@RequestMapping("geren-geRen-ziLiao.html")
	public String gerenGeRenZiLiao(HttpServletRequest request) {
		Object id = request.getSession().getAttribute("userid");
		request.setAttribute("id", id);
		return "/modules/repository/geren_geRen_ziLiao";
	}

	// 系统管理 -->用户管理-->默认跳转 查询页面
	@RequestMapping("houtaiUser.html")
	public String toUserGuanLi() {
		return "/modules/repository/user_guan_li";
	}

	// 系统管理 -->用户管理-->更新 新增 页面
	@RequestMapping("user-add-update.html")
	public String toUserAddAndUpdate(HttpServletRequest request, Model model) {
		String id = request.getParameter("id");
		if(id!=null && id !=null && !"".equals(id) && !"0".equals(id)){
			request.setAttribute("id", id);
		}else{
			request.setAttribute("id", "");
		}
		return "/modules/repository/user_add_update";
	}

	// 系统管理 -->用户管理-->更新 新增 页面 树形部门查询
	@RequestMapping("user-editSave-department-zTree.html")
	public String touserEditSaveDepartmentZTree() {
		return "/modules/repository/user_editSave_department_zTree";
	}

	// 系统管理 -->用户管理-->更新 新增 页面 树形部门查询
	@RequestMapping("user-editSave-userGroup-zTree.html")
	public String userEditSaveUserGroupZTree() {
		return "/modules/repository/user_editSave_userGroup_zTree";
	}


	@RequestMapping("user-menu-logGuanLi.html")
	public String tologGuanLi() {
		return "/modules/repository/log_guanLi";
	}


	Integer newUserId; // 所登录的用户ID

	
	// 查询所有菜单管理的Classes
		@RequestMapping("KnowledgemenuListall")
		public void toKnowledgemenuListall(HttpServletRequest request,
				HttpServletResponse response) throws Exception {
			Integer userid = (Integer) request.getSession().getAttribute("userid");
			List<UserRole> aUserRole = publicService.getUserRole();
			String temp1 = "";
			for (int i = 0; i < aUserRole.size(); i++) {
				UserRole bUserRole = aUserRole.get(i);
				if (bUserRole.getUserId().equals(userid)) {
					List<Permission> aPermission = publicService.getPermission();
					for (int j = 0; j < aPermission.size(); j++) {
						Permission bPermission = aPermission.get(j);
						if (bUserRole.getRoleId().equals(bPermission.getRoleId())) {
							temp1 += bPermission.getMenuIds() + ",";
						}
					}
				}
			}
			List<String> list2 = new ArrayList<String>();
			if (!"".equals(temp1)) {
				temp1 = temp1.substring(0, temp1.length() - 1);
				String[] temp = temp1.split(",");

				for (int i = 0; i < temp.length; i++) {
					if (!list2.contains(temp[i]))
						list2.add(temp[i]);
				}
			}
			List<Menu> list1 = publicService.getMenu();
			List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
			LinkedHashMap<String, Object> mp = null;
			for (int i = 0; i < list1.size(); i++) {
				Menu aMenu = list1.get(i);
				boolean flag = false;
				for (int j = 0; j < list2.size(); j++) {

					if (list2.get(j).equals(aMenu.getId().toString())) {
						flag = true;
						break;
					}
				}
				if (flag) {
					mp = new LinkedHashMap<String, Object>();
					mp.put("id", aMenu.getId());
					mp.put("url", aMenu.getUrl());
					mp.put("name", aMenu.getName());
					mp.put("icon", aMenu.getIcon());
					mp.put("pId", aMenu.getParentId());
					r.add(mp);
				}
			}
			LinkedHashMap<String, Object> mp2 = null;
			mp2 = new LinkedHashMap<String, Object>();
			mp2.put("id", 0);
			mp2.put("name", "123");
			mp2.put("url", "123");
			mp2.put("icon", "123");
			mp2.put("pId", 999999);
			String result = TreeJsion.get(mp2, r);
			// System.out.println(r);
			// System.out.println(result);
			super.pringWriterToPage(result.toString(), "application/json", response);

		}
	
	/**
	 * 实现 用户管理
	 */
	// 系统管理 -->用户管理 -->默认查询页面
	@RequestMapping("userfindAll")
	@ResponseBody
	public void userfindAll(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		Integer pageNumber = 15;
		Integer pageSize = Integer.parseInt(request.getParameter("page"));
		String nickName = request.getParameter("nickName");
		String username = request.getParameter("username");
		String telephone = request.getParameter("telephone");
		String status = request.getParameter("status");

		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if (username != null && !"".equals(username)) {
			queryParams.put("=,username", username);
		}
		if (nickName != null && !"".equals(nickName)) {
			queryParams.put("=,nickName", nickName);
		}
		if (telephone != null && !"".equals(telephone)) {
			queryParams.put("=,telephone", telephone);
		}
		if (status != null && !"".equals(status)) {
			queryParams.put("=,status", status);
		}
		queryParams.put("^,id", "desc");
		String uid = request.getSession().getAttribute("userid")+"";
		if(!"1".equals(uid)){
			queryParams.put("!,username", "root");
		}
		Integer count = publicService.getUserCount(queryParams);
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		List<User> list = publicService.getUser(queryParams, pageSize,
				pageNumber);
		for (int i = 0; i < list.size(); i++) {
			User aUser = list.get(i);
			mp = new LinkedHashMap<String, Object>();
			mp.put("id", aUser.getId());
			mp.put("username", aUser.getUsername());
			mp.put("nickName", aUser.getNickName());
			mp.put("telephone", aUser.getTelephone());
			mp.put("email", aUser.getEmail());
			mp.put("createTime", aUser.getCreateTime());
			mp.put("signature", aUser.getSignature());
			mp.put("description", aUser.getDescription());
			mp.put("gender", aUser.getGender());
			mp.put("realName", aUser.getRealName());
			mp.put("status", aUser.getStatus());
			mp.put("type", aUser.getType());
			mp.put("avatarImg", FILESERVER+aUser.getAvatarImg());
			r.add(mp);
			mp=null;
		}

		String result = formatToJson(r);
		StringBuffer sb = new StringBuffer();
		int listsize = r.size();
		sb.append("{\"listsize\":" + listsize + ",");
		sb.append("\"pageSize\":"
				+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}

	// 系统管理 -->用户管理 -->添加 and 更新用户
	@RequestMapping("userAddandUpdate")
	@ResponseBody
	public void userAdd(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		String description = request.getParameter("description");
		String email = request.getParameter("email");
		String gender = request.getParameter("gender");
		String nickName = request.getParameter("nickName");
		String password = request.getParameter("password");
		String realName = request.getParameter("realName");
		String signature = request.getParameter("signature");
		String telephone = request.getParameter("telephone");
		String type = request.getParameter("type");
		String username = request.getParameter("username");
		String avatarImg = request.getParameter("avatarImg");
		
		HashMap<String, String>r=new HashMap<String, String>();
		try {
			if(id==null || "".equals(id)){//新增
				User user = new User();
				user.setAvatarImg(avatarImg==null?"":avatarImg.replace(FILESERVER, "").replace(FILEPATH, "").replace("//", "/"));
				user.setCreateTime(DateUtils.getDateTime());
				user.setDescription(description);
				user.setEmail(email);
				user.setGender(Integer.parseInt(gender));
				user.setNickName(nickName);
				user.setPassword(MD5.convert(password));
				user.setRealName(realName);
				user.setSignature(signature);
				user.setStatus(0);

				user.setTelephone(telephone);
				user.setType(Integer.parseInt(type));
				user.setUsername(username);
				baseService.saveUser(user);
				
				HashMap<String, Object> queryParams = new HashMap<String, Object>();
				queryParams.put("=,username", username);
				queryParams.put("=,telephone", telephone);
				List<User> user2 = publicService.getUser(queryParams , 1, 1);
				if("0".equals(type)){//管理员
					UserRole userRole = new UserRole();
					userRole.setUserId(user2.get(0).getId());
					userRole.setRoleId(2);
					baseService.saveUserRole(userRole);
				}else if("1".equals(type)){//教师
					UserRole userRole = new UserRole();
					userRole.setUserId(user2.get(0).getId());
					userRole.setRoleId(3);
					baseService.saveUserRole(userRole);
				}
			}else{//编辑
				User user = publicService.findUser(Integer.parseInt(id));
				user.setAvatarImg(avatarImg==null?"":avatarImg.replace(FILESERVER, "").replace(FILEPATH, "").replace("//", "/"));
				user.setCreateTime(DateUtils.getDateTime());
				user.setDescription(description);
				user.setEmail(email);
				user.setGender(Integer.parseInt(gender));
				user.setNickName(nickName);
				if(password!=null && !"".equals(password)){
					user.setPassword(MD5.convert(password));
				}
				user.setRealName(realName);
				user.setSignature(signature);
				user.setStatus(0);
				user.setTelephone(telephone);
				user.setType(Integer.parseInt(type));
				/*if(Integer.parseInt(type) == user.getType()){
					user.setType(Integer.parseInt(type));
				}else{
					HashMap<String, Object> queryParams = new HashMap<String, Object>();
					queryParams.put("=,userId", user.getId());
					List<UserRole> userRoles = publicService.getUserRole(queryParams);
					for (UserRole userRole : userRoles) {
						if("0".equals(type)){
							userRole.setRoleId(3);
							baseService.editUserRole(userRole);
						}else{
							userRole.setRoleId(4);
							baseService.editUserRole(userRole);
						}
					}
				}*/
				user.setUsername(username);
				baseService.editUser(user);
			}
			r.put("result", "success");
			r.put("msg", "保存成功");
		} catch (Exception e) {
			r.put("result", "fail");
			r.put("msg", "保存失败");
		}
		
		String result = formatToJson(r);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 判断用户名不能重复
	@RequestMapping("UserPanDuan")
	@ResponseBody
	public void toUserPanDuan(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String username = request.getParameter("username").trim();
		LinkedHashMap<String, Object> mp = new LinkedHashMap<String, Object>();
		List<User> list = publicService.getUser();
		for (int i = 0; i < list.size(); i++) {
			User user = list.get(i);
			if (username.equals(user.getUsername())) {
				mp.put("tishi", "0");
				break;
			} else {
				mp.put("tishi", "1");
			}
		}
		String result = formatToJson(mp);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 获取更新内容 并显示到网页
	@RequestMapping("userfindone")
	public void toUserFindOne(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		HashMap<String, Object> m = new HashMap<String, Object>();
		String id = request.getParameter("id");
		if(id!=null && !"".equals(id)){
			User user = publicService.findUser(Integer.parseInt(id));
			if(user!=null){
				m.put("id", user.getId());
				m.put("avatarImg", FILESERVER+user.getAvatarImg());
				m.put("description", user.getDescription());
				m.put("email", user.getEmail());
				m.put("gender", user.getGender());
				m.put("nickName", user.getNickName());
				m.put("password", user.getPassword());
				m.put("realName", user.getRealName());
				m.put("signature", user.getSignature());
				m.put("telephone", user.getTelephone());
				m.put("type", user.getType());
				m.put("username", user.getUsername());
			}
		}
		String result = formatToJson(m);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 删除单个用户
	@RequestMapping("userdel")
	public void toUserDel(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		HashMap<String, String>r=new HashMap<String, String>();
		try {
			boolean flag=true;
			
			Integer courseCount = publicService.getCourseCount(queryParams);
			List<Course> courses = publicService.getCourse(queryParams, 1, courseCount);
			for (Course course : courses) {
				if(course.getUserIds()!=null){
					String[] splits = course.getUserIds().split(";");
					for (String string : splits) {
						if(string.equals(id)){
							flag=false;
							break;
						}
					}
				}
				if(!flag){
					break;
				}
			}
			if(flag){
				Integer classesOnlineCount = publicService.getClassesOnlineCount(queryParams);
				List<ClassesOnline> classesOnlines = publicService.getClassesOnline(queryParams, 1, classesOnlineCount);
				for (ClassesOnline classesOnline : classesOnlines) {
					if(classesOnline.getUserIds()!=null){
						String[] splits = classesOnline.getUserIds().split(";");
						for (String string : splits) {
							if(string.equals(id)){
								flag=false;
								break;
							}
						}
					}
					if(!flag){
						break;
					}
				}
			}
			if(flag){
				queryParams.put("=,userId", id);
				List<UserRole> listUserRole = publicService.getUserRole(queryParams);
				for (UserRole ur : listUserRole) {
					baseService.deleteUserRole(ur);
				}
				User user = new User();
				user = publicService.findUser(Integer.parseInt(id));
			
				baseService.deleteUser(user);
				r.put("result", "success");
				r.put("msg", "操作成功");
			}else{
				r.put("result", "fail");
				r.put("msg", "有关联课程或网班，不能删除");
			}
		} catch (Exception e) {
			r.put("result", "fail");
			r.put("msg", "操作失败");
		}
		String result = formatToJson(r);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 获取当前时间
	@RequestMapping("newDate")
	public void toNewDate(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = sdf.format(new java.util.Date());
		String result = "{\"date\":\"" + date + "\"}";
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	
	// 用户登录 页面
	@RequestMapping("userlogin")
	public void toUserlogin(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String username = request.getParameter("username");
		String kaptcha = request.getParameter("kaptcha");
		String type = request.getParameter("type");
		String password = MD5.convert(request.getParameter("password"));
		
		Cookie cookie = new Cookie("ticket",MD5.string2MD5(username+"∷"+password));
        cookie.setMaxAge(60*60*24*180);// 设置为180day
        cookie.setPath("/");
        cookie.setDomain(request.getServerName());
        response.addCookie(cookie);
        
        Cookie cookieUserName = new Cookie("ticketUserName",username);
        cookieUserName.setMaxAge(60*60*24*180);// 设置为180day
        cookieUserName.setPath("/");
        cookieUserName.setDomain(request.getServerName());
        response.addCookie(cookieUserName);
		HashMap<String, Object> user = new HashMap<String, Object>();


		// if(stipulateTime.after(nowTime)){
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("=,username", username);
		queryParams.put("=,password", password);
		List<User> users = publicService.getUser(queryParams, 1, 1);
		

		HttpSession session = request.getSession();
		String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
		boolean kaptchaBoolean = false;
		boolean pad = false;
		int count = 0;
		Object sessionOne = request.getSession().getAttribute("kaptchaTime");
		if (sessionOne != null) {
			count = Integer.parseInt(String.valueOf(sessionOne));
		} else {
			request.getSession().setAttribute("kaptchaTime", 0);
		}
		/*if (count <= 2) {
			pad = true;
		}*/
		// 判断为NULL 或者“” StringUtils.isBlank(kaptcha)
		if (kaptcha.equals(code) || pad == true) {
			if (users.size() > 0) {
				User u = users.get(0);
				if(u.getStatus()==1){
					user.put("msg", "账户还未审核通过");
					user.put("tishi", "error");
				}else if(u.getType()!=Integer.parseInt(type)){
					user.put("msg", "用户类型错误");
					user.put("tishi", "error");
				}else{
					List<UserRole> userRole = publicService.getUserRole();
					for (UserRole userRole2 : userRole) {
						if(userRole2.getUserId() == u.getId()){
							if(userRole2.getRoleId()==1){
								request.getSession().setAttribute("userType","超级管理员");
							}else if(userRole2.getRoleId()==2){
								request.getSession().setAttribute("userType","管理员");
							}else if(userRole2.getRoleId()==3){
								request.getSession().setAttribute("userType","教师");
							}
						}
					}
					
					
					
					user.put("username", u.getNickName());
					user.put("userid", u.getId());
					request.getSession().setAttribute("username",u.getNickName());
					request.getSession().setAttribute("userkk", u.getNickName());
					request.getSession().setAttribute("userid", u.getId());
					request.getSession().setAttribute("usertypevalue", u.getType());
					user.put("tishi", "ok");
					kaptchaBoolean = true;
					request.getSession().setAttribute("kaptchaTime", 0);
				}
				
			} else {
				user.put("tishi", "no");
				user.put("msg", "用户名或密码错误");
			}
		} else {
			user.put("tishi", "kaptcha");
			user.put("msg", "验证码错误");
		}
		if (kaptchaBoolean == false) {
			count = count + 1;
			request.getSession().setAttribute("kaptchaTime", count);
			user.put("kaptchaTime", count);
		}
		String result = formatToJson(user);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 配置 layout.html 用户权限
	@RequestMapping("loginLayout")
	public void tologinLayout(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// response.sendRedirect("login.html");
		User u = publicService.findUser((Integer) request.getSession()
				.getAttribute("userid"));
		request.getSession().setAttribute("username", null);
		request.getSession().setAttribute("userid", null);
		request.getSession().setAttribute("departmentid", null);
		HashMap<String, Object> user = new HashMap<String, Object>();
		user.put("tishi", "ok");
//		this.Log(u.getId(), "logout", null, null, "【" + u.getUsername()
//				+ "】安全退出！", 0);
		String result = formatToJson(user);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	

	/**
	 * ******************** 格式化JSON
	 */
	private boolean isTab = true;

	public String stringToJSON(String strJson) {
		// 计数tab的个数
		int tabNum = 0;
		StringBuffer jsonFormat = new StringBuffer();
		int length = strJson.length();
		for (int i = 0; i < length; i++) {
			char c = strJson.charAt(i);
			if (c == '{') {
				tabNum++;
				jsonFormat.append(c + "</br>");
				jsonFormat.append(getSpaceOrTab(tabNum));
			} else if (c == '}') {
				tabNum--;
				jsonFormat.append("</br>");
				jsonFormat.append(getSpaceOrTab(tabNum));
				jsonFormat.append(c);
			} else if (c == ',') {
				jsonFormat.append(c + "</br>");
				jsonFormat.append(getSpaceOrTab(tabNum));
			} else {
				jsonFormat.append(c);
			}
		}
		return jsonFormat.toString();
	}

	// 是空格还是tab
	public String getSpaceOrTab(int tabNum) {
		StringBuffer sbTab = new StringBuffer();
		for (int i = 0; i < tabNum; i++) {
			if (isTab) {
				sbTab.append("&nbsp;");
			} else {
				sbTab.append("    ");
			}
		}
		return sbTab.toString();
	}

	/**
	 * end *************
	 */
}
